package com.zy.struts.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.zy.struts.dao.DAOFactory;
import com.zy.struts.dao.MessageDAO;
import com.zy.struts.dao.UserDAO;
import com.zy.struts.domain.Message;
import com.zy.struts.domain.User;

public class ChangeInfoAction extends ActionSupport {

	private String msg;
	private String reciverId;

	public String changeInfo(){
		System.out.println("reciverId:"+reciverId);
		HttpServletRequest request=(HttpServletRequest)ServletActionContext.getRequest();
		reciverId=(String)request.getAttribute("reciverId");
		System.out.println("reciverId:"+reciverId);
		Message message=new Message();
		message.setMsgTime(new Date());
		message.setMsg(msg);
		UserDAO uDao=(UserDAO)DAOFactory.getInstance().getDAO("UserDAO");
		User reciver=uDao.getUser(reciverId);
		User sender=(User)ActionContext.getContext().getSession().get("user");
		message.setSenderId(sender);
		message.setReciverId(reciver);
		
		MessageDAO mDao=(MessageDAO)DAOFactory.getInstance().getDAO("MessageDAO");
		mDao.addMessage(message);
		
		return null;
	}

	public String getMessage(){
		System.out.println("*********get Message*************");
		User user=(User)ActionContext.getContext().getSession().get("user");
		
		MessageDAO mDao=(MessageDAO)DAOFactory.getInstance().getDAO("MessageDAO");
		List<Message> list=mDao.getMessages(user);
		System.out.println("sender message size:"+list.size());
		HttpServletResponse response=ServletActionContext.getResponse();
		response.setContentType("text/xml");
		try {
			PrintWriter out=response.getWriter();
			StringBuffer msg=new StringBuffer();
			msg.append("<messages>");
			for (Message message : list) {
				msg.append("<message>");
				msg.append("<id>");
				msg.append(message.getSenderId().getId());
				msg.append("</id>");
				msg.append("<sender>");
				msg.append(message.getSenderId().getName());
				msg.append("</sender>");
				msg.append("<content>");
				msg.append(message.getMsg());
				msg.append("</content>");
				msg.append("</message>");
			}
			msg.append("</messages>");
			System.out.println("**get message**"+msg.toString());
			out.write(msg.toString());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public String getReciverId() {
		return reciverId;
	}

	public void setReciverId(String reciverId) {
		this.reciverId = reciverId;
	}

}
